<template>
  <el-collapse v-model="activeName" accordion>
    <el-collapse-item title="还车结算" name="1">
      <div style="padding: 20px">
        <!--待扣费用-->
        <withheldExpense :rule-form="ruleForm" @waitAmountInput="waitAmountInput"/>

        <el-form :model="ruleForm" ref="ruleForm" :label-position="labelPosition" :class="isEdit?'':'formItem'">

          <!--查询关联订单-->
          <el-row :gutter="24">
            <el-col :span="24">
              <el-button type="primary" @click="boolBut = !boolBut" size="mini">查询关联订单</el-button>
              <el-tooltip style="padding-left: 10px" class="item" effect="dark" content="点击展示主订单下其他订单"
                          placement="top-start">
                <i class="el-icon-question"/>
              </el-tooltip>
            </el-col>
            <el-col :span="24" v-if="boolBut">
              <orderTable :rule-form="ruleForm"/>
            </el-col>
          </el-row>

          <!--保证金抵扣-->
          <el-row :gutter="24">
            <el-col :span="24">
              <span class="header-card-title">保证金抵扣</span>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆保证金:" prop="deposit"
                            :rules="{required:state === 'write',message:'请输入车辆保证金' ,trigger:'blur'}">
                <el-input disabled v-if="isEdit" :value="handleThousand(ruleForm.deposit)"/>
                <span v-else> {{ format_thousand(ruleForm.deposit) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否使用保证金抵扣:" prop="deductionStatus"
                            :rules="{required:state === 'write',message:'请选择是否使用保证金抵扣' ,trigger:'blur'}">
                <el-radio-group v-if="isEdit" @input="handleRadio" v-model="ruleForm.deductionStatus">
                  <el-radio v-if="ruleForm.returnCategory !== '5'" label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
                <span v-else>{{ ruleForm.deductionStatus === 1 ? '是' : '否' }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!--自定义减免项-->
          <el-row :gutter="24">
            <el-col :span="24">
              <span class="header-card-title">自定义减免项</span>
            </el-col>

            <el-col :span="24">
              <el-table :data="ruleForm.returnCarReductionList" border size='mini'
                        :header-cell-class-name="headerClass">

                <el-table-column align="center" label="操作" width="80" v-if="isEdit">
                  <template #default="{row,$index}">
                    <i class="el-icon-delete" style="color: red;cursor:pointer;font-size: 16px"
                       @click="handleDele($index)"/>
                  </template>
                </el-table-column>

                <el-table-column align="center" prop="reductionName" label="减免项名称">
                  <template #default="{row,$index}">
                    <el-form-item class="formTable" :prop="`returnCarReductionList.${$index}.reductionName`"
                                  :rules="{required:state === 'write',trigger:'blur'}">
                      <el-select v-model="row.reductionName" v-if="isEdit" style="width: 100%"
                                 @change="handleSelect(row, $index)" placeholder="请选择减免项"
                                 size="mini">
                        <el-option v-for="item in returnCarDepositDictVoList" :label="item.dictLabel"
                                   :value="item.dictValue"
                                   :key="item.dictValue"/>

                      </el-select>
                      <span v-else>{{
                          selectDictLabel(returnCarDepositDictVoList, row.reductionName) || '-'
                        }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>

                <el-table-column label="可减免金额" prop="unpaidFee" show-overflow-tooltip align="center">
                  <template #default="{row}">
                    {{ format_thousand(row.unpaidFee) }}
                  </template>
                </el-table-column>

                <el-table-column align="center" prop="reductionAmount" label="减免金额">
                  <template #default="{row,$index}">
                    <el-form-item class="formTable" :prop="`returnCarReductionList.${$index}.reductionAmount`"
                                  :rules="{required:state === 'write',trigger:'blur'}">
                      <el-input-number v-thousand v-if="isEdit" v-model="row.reductionAmount"
                                       placeholder="请输入减免金额"
                                       :ref="`reductionAmount${$index}`"
                                       @change="handleTable(row,'reductionAmount',$index)"
                                       :min="0" :max="Number(row.unpaidFee) ? Number(row.unpaidFee) : 0" :step="100"
                                       style="width: 100%"/>
                      <span v-else> {{ format_thousand(row.reductionAmount) }}</span>
                    </el-form-item>

                  </template>
                </el-table-column>

                <el-table-column align="center" show-overflow-tooltip prop="reductionReason" label="减免原因">
                  <template #default="{row,$index}">
                    <el-form-item class="formTable" :prop="`returnCarReductionList.${$index}.reductionReason`"
                                  :rules="{required:state === 'write',trigger:'blur'}">
                      <el-input v-if="isEdit" v-model="row.reductionReason" :maxlength="255"/>
                      <span v-else> {{ row.reductionReason }}</span>
                    </el-form-item>
                  </template>
                </el-table-column>

                <template v-slot:append
                          v-if="handleIs(ruleForm.returnCarReductionList,returnCarDepositDictVoList)">
                  <div class="flex-xy-center" style="height: 40px">
                    <div style="display: flex">
                      <e-button type="text" style="margin-right: 20px" icon="eel-icon-plus"
                                @click="handleTableColumn">添加
                      </e-button>
                    </div>

                  </div>
                </template>
              </el-table>
            </el-col>

            <el-col :span="24">
              <el-form-item label="情况说明:">
                <image-common v-model="ruleForm.situationDescriptionFile" :disabled="!isEdit" :limit="20" :upType="2"/>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="应退金额:" prop="returnFee"
                            :rules="{required:state === 'write',message:'请输入应退金额' ,trigger:'blur'}">
                <el-input v-if="isEdit" disabled :value="handleThousand(ruleForm.returnFee)"/>
                <span v-else> {{ format_thousand(ruleForm.returnFee) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="补缴金额:" prop="paymentFee"
                            :rules="{required:state === 'write',message:'请输入补缴金额' ,trigger:'blur'}">
                <el-input v-if="isEdit" disabled :value="handleThousand(ruleForm.paymentFee)"/>
                <span v-else> {{ format_thousand(ruleForm.paymentFee) }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!--退款账户-->
          <el-row :gutter="24">
            <el-col :span="24">
              <span class="header-card-title">退款账户</span>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户银行:" prop="bankName"
                            :rules="{required:state === 'write',message:'请输入开户银行' ,trigger:'blur'}">
<!--                <el-input v-if="isEdit" v-model="ruleForm.bankName"/>-->
                <el-input v-if="isEdit" @focus="select_dialog" v-model="ruleForm.bankName" ref="selectDialogInput"
                          clearable @clear="clear" placeholder="请选择开户银行"/>
                <span v-else> {{ ruleForm.bankName || '-' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账户:" prop="account"
                            :rules="{required:state === 'write',message:'请输入账户' ,trigger:'blur'}">
                <el-input v-if="isEdit" v-model="ruleForm.account"/>
                <span v-else> {{ ruleForm.account || '-' }}</span>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>

      </div>
    </el-collapse-item>
  </el-collapse>
</template>

<script>
import * as apis from "@/api/returnMargin";
import {toNumberSub} from "@/utils/utils"

export default {
  name: "returnCarSettleMessage", //还车结算
  dicts: ["deduction_tye"],
  components: {
    withheldExpense: () => import("./withheldExpense.vue"),
    orderTable: () => import("./orderTable.vue"),
  },
  props: {
    value: {
      type: Object,
      default: () => {
        return {};
      },
    },
    state: {
      type: String,
      default: "",
    },
  },

  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key, value) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.state === "write") {
        return "top";
      } else {
        return "right";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
    handleThousand() {
      return function (val) {
        return val ? this.format_thousand(val) : 0
      };
    },
    handleIs() {
      return function (list, arr) {
        if (list && list.length !== arr.length && this.isEdit) {
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    "value.orderCarNo": {
      handler(val) {
        if (val && this.num === 0) {
          this.num = 1;
          this.handleReturnCarDepositList();
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      activeName: ["1"],
      boolBut: false,
      returnCarDepositDictVoList: [],
      num: 0,
      headerList: ["reductionName", "reductionAmount", "reductionReason"],
      waitAmount: 0
    };
  },
  created() {
  },
  mounted() {
    setTimeout(() => {
      this.handleCount()
    }, 1000)
  },
  methods: {
    select_dialog() {
      this.$refs.selectDialogInput.blur();
      const SelectDialog =
          require('../../../components/A/A-form/template/index').default;

      SelectDialog({type: 'bank'})
          .then(({data, type}) => {
            this.ruleForm.bankName = this.value.bankName = data.bankName;
            this.ruleForm.bankCode = this.value.bankCode = data.bankCode;
          })
          .catch(err => {
          });
    },

    clear() {
      this.ruleForm.bankName = this.value.bankName = '';
      this.ruleForm.bankCode = this.value.bankCode = '';
    },

    waitAmountInput(val) {
      this.ruleForm.waitAmount = this.value.waitAmount = this.waitAmount = val
    },

    headerClass({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < row.length; i++) {
        if (
            this.headerList.includes(row[i].property) &&
            i == columnIndex &&
            this.isEdit
        ) {
          return "header-class";
        }
      }
    },

    handleRadio(val) {
      this.ruleForm.deductionStatus = this.value.deductionStatus = val
      this.handleCount()
    },

    async handleReturnCarDepositList() {
      try {
        let res = await apis?.queryByOrderCarNo(this.value.orderCarNo);
        this.returnCarDepositDictVoList = res.data || [];
      } catch (e) {
        console.log(e);
      }
    },

    handleSelect(row, index) {
      let obj = this.returnCarDepositDictVoList.filter(a => a.dictValue === row.reductionName)[0]
      row.unpaidFee = Number(obj.unpaidFee)
      row.reductionAmount = 0
      for (let i = 0; i < this.value.returnCarReductionList.length; i++) {
        let code = this.value.returnCarReductionList[i].reductionName;
        if (index !== i && code === row.reductionName) {
          this.$message({
            type: "warning",
            message: "减免项名称已存在",
          });
          row.reductionName = ''
          row.unpaidFee = ''
          break
        }
      }
    },

    handleTable(row, key, index) {
      row[key] = (Math.round(row[key] * 100) / 100)
      let ref = `reductionAmount${index}`
      setTimeout(() => {
        this.$refs[ref].focus()
      }, 300)
      this.handleCount()
    },

    handleCount() {
      let num = 0;
      if (this.ruleForm.returnCarReductionList && this.ruleForm.returnCarReductionList.length > 0) {
        num = this.ruleForm.returnCarReductionList.reduce((acc, item) => acc + (Number(item.reductionAmount) * 100), 0);
      }

      num = (num / 100).toFixed(2)

      const depositNumber = Number(this.ruleForm.deposit); //车辆保证金
      const waitAmountNumber = Number(this.waitAmount);  //剩余未缴纳

      const setValues = (returnFee, paymentFee) => {
        this.value.returnFee = this.ruleForm.returnFee = this.ruleForm.returnCategory === '5' ? 0 : Math.abs(returnFee);
        this.value.paymentFee = this.ruleForm.paymentFee = Math.abs(paymentFee);
      };

      // 剩余未缴纳 -自定义减免项
      let c = toNumberSub(waitAmountNumber, num)
      if (this.value.deductionStatus === '1') { //是
        let a = toNumberSub(depositNumber, c)    //depositNumber - (waitAmountNumber - num);
        if (a > 0) {
          setValues(a, 0);
        } else {
          setValues(0, a);
        }
      } else if (this.value.deductionStatus === '0') {  //否
        setValues(depositNumber, c)  //(depositNumber, waitAmountNumber - num);
      } else {
        setValues(0, 0);
      }
    },

    handleDele(index) {
      this.ruleForm.returnCarReductionList.splice(index, 1);
      this.handleCount()
    },

    handleTableColumn() {
      let obj = {
        orderCarNo: "",
        carNo: "",
        returnCarDepositId: "",
        unpaidFee: "",
        reductionName: "",
        reductionAmount: "",
        reductionReason: "",
      };
      this.ruleForm.returnCarReductionList.push(obj);
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr();
            reject();
          }
        });
      });
    },

    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth",
        });
      });
    },

    valid() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

::v-deep .el-collapse {
  margin-bottom: 0;
  padding-bottom: 0;

}

::v-deep .el-collapse-item__header {
  padding-left: 20px !important;
}

::v-deep .el-collapse-item__content {
  padding-bottom: 0 !important;
}

::v-deep .header-class {
  .cell::before {
    content: "*";
    color: red;
    padding-right: 2px;
    font-size: 14px;
  }
}
</style>


